<template>
  <div id="main" class="mod-config" style="padding-bottom: 10px;height:100%">
    <div class="app-title">
      <el-avatar :size="32" :src="userInfo.avatar+'_60x60q90.jpg'" style="float: left;"></el-avatar>
      <div style="float:left;padding: 8px;">任务清单v1.0</div>
      <i class="el-icon-question" style="float:left;padding:8px 0px;" @click="navHelper()"></i>
      <el-input v-if="listFlag!=3" placeholder="任务内容搜索" v-model="query.keyword" clearable size="small" style="width: 180px; float:right; margin-top: 2px;"
                @clear="clearSearch" @keyup.enter.native="search">
        <el-button slot="append" icon="el-icon-search" size="small" @click="search"></el-button>
      </el-input>
    </div>

      <div class="pj_container" :style="getStyle()">
        <div v-if="listFlag==3">
          <el-calendar v-model="dataForm.endDate">
            <template
              slot="dateCell"
              slot-scope="{date, data}">
              <div>
                <div>{{data.day.split('-').slice(2).join('.') }}
                  <span style="color: #3a8ee6" v-if="getHasDoListByDay(date).length>0 && getTodoListByDay(date).length==0">*</span>
                  <span style="color: red" v-if="getTodoListByDay(date).length>0 ">*</span>
                </div>
              </div>
            </template>
          </el-calendar>
        </div>
        <div id="todo-task-panel" >
          <transition-group name="task-list" tag="table" class="task-table">
            <tr v-bind:key="0" style="height: 1px">
              <td style="width:40px;"></td>
              <td style="font-size: 14px;">
                <div v-if="listFlag!=3">
                  <el-link type="primary" @click="showTodayTodo()" :underline="false"> 今日待办{{getTodayTodoList().length}}项</el-link> &nbsp;
                  <el-link type="primary" @click="showAllTodo()" :underline="false"> 待办{{todoCount}}项</el-link> &nbsp;
                  <el-link type="warning" @click="showExpiredList()" :underline="false"> 逾期{{getExpiredList().length}}项</el-link>
                </div>
              </td>
              <td style="width:40px;padding: 0">

              </td>
            </tr>
            <tr v-for="(item,index) in getToDoList()" v-bind:key="item.id" :class="(dataLoading0||listFlag==3)?``:`task-list-item`">
              <td style="width:40px; ">
                <el-checkbox v-model="item.flag" style="margin-top: 2px;" @change="setTaskStatus(item)"></el-checkbox>
              </td>
              <td @click="showPanel2(item)">
                <div>{{item.name}}</div>
                <div class="small">备注：{{item.remark}}</div>
                <div class="small">{{item.endDate}} {{getAssigneeStr(item)}}</div>
              </td>
              <td style="width:40px; text-align: center">
                <i :class="`${item.star?'el-icon-star-on':'el-icon-star-off'}`" @click="setTaskStar(item)"></i>
              </td>
            </tr>
          </transition-group>
        </div>
        <div style="background-color: #EBEFFB; padding: 8px 30px; cursor:pointer; color: gray; font-size: 15px; margin: 10px 0;" @click="showCompleted =!showCompleted">
          <i v-if="!showCompleted" class="el-icon-circle-plus-outline"></i>
          <i v-if="showCompleted" class="el-icon-remove-outline"></i>
          已完成
        </div>
        <div id="hasDo-task-panel" v-if="showCompleted" style="color: lightgray; ">
          <table class="task-table">
            <tr v-for="(item,index) in pageHasDoList()">
              <td style="width:40px; ">
                <el-checkbox v-model="item.flag" style="margin-top: 2px;" @change="setTaskStatus(item)"></el-checkbox>
              </td>
              <td @click="showPanel2(item)">
                <div>{{item.name}}</div>
                <div class="small" style="color: lightgray">备注：{{item.remark}}</div>
                <div class="small" style="color: lightgray">{{getAssigneeStr(item)}} 完成时间：{{item.completedDate}}</div> <!-- 截止时间：{{item.endDate}}-->
              </td>
              <td style="width:40px; text-align: center">
                <i :class="`${item.star?'el-icon-star-on':'el-icon-star-off'}`" ></i>
              </td>
            </tr>
          </table>
          <div v-if="query.page<totalPage && listFlag!=3" style="padding: 10px; text-align: center; cursor:pointer;" @click="loadMore">点此查看更多</div>
        </div>
      </div>
      <div class="drawer-right" v-if="detailMode">
        <div class="sub-title">
          <i class="el-icon-right" style="float:left; padding: 13px; font-size: 20px;" @click="detailMode=false"></i>
        </div>
          <div>
            <el-form ref="form" label-width="80px" :disabled="dataForm.flag">
              <el-form-item label="任务内容">
                <el-input ref="txtTask" type="textarea" :autosize="{ minRows: 1, maxRows: 3}" v-model="dataForm.name"
                          placeholder="任务内容" >  <!--@keyup.enter.native="saveTask"-->
                </el-input>
              </el-form-item>
              <el-form-item label="创建人">
                <span>{{dataForm.creatorName}}</span>
              </el-form-item>
              <el-form-item label="创建时间">
                <span>{{dataForm.createAt}}</span>
              </el-form-item>
              <el-form-item label="任务状态">
                <el-checkbox v-model="dataForm.flag" @change="setTaskStatus(dataForm)">是否结束</el-checkbox>
              </el-form-item>
              <el-form-item label="截止日期">
                <el-date-picker
                  v-model="dataForm.endDate"
                  align="right"
                  type="date"
                  placeholder="选择日期"
                 >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="指派对象">
                <i class="el-icon-user" style="width: 130px; padding: 5px; font-size: 18px;" @click="selectDingUser">
                  <span style="font-size: 14px;padding: 10px 0;">
                    {{ dataForm.assigneeName }}
                  </span>
                </i>
              </el-form-item>
              <el-form-item label="是否重要">
                <i :class="`${dataForm.star?'el-icon-star-on':'el-icon-star-off'}`" @click="toggleStar"></i>
              </el-form-item>
              <el-form-item label="备注">
                <el-input type="textarea" :autosize="{ minRows: 1, maxRows: 3}" v-model="dataForm.remark"
                          placeholder="备注" >  <!--@keyup.enter.native="saveTask"-->
                </el-input>
              </el-form-item>
            </el-form>
            <div style="text-align: center">
              <el-button style="width:120px;" v-if="!dataForm.flag" type="primary" @click="saveTask()" >保存</el-button>
              <el-button style="width:120px; margin-left: 20px;"  type="primary" @click="detailMode=false" >返回</el-button>
            </div>
        </div>
      </div>

    <el-backtop :right="20" :bottom="180"></el-backtop>
    <div v-if="addVisible" class=".el-message-box__wrapper" >
      <div class="v-modal" @click.stop="addVisible = false"></div>
      <div class="add-tool">
        <div style="margin-right: 60px;">
          <el-input ref="txtTask" type="textarea" :autosize="{ minRows: 1, maxRows: 3}" v-model="dataForm.name"
                    placeholder="任务内容"  @focus="closeToolBox">  <!--@keyup.enter.native="saveTask"-->
          </el-input>
        </div>
        <div class="tool-box">
          <i class="el-icon-time" @click="toolBoxVisible=true" style="width: 150px;">
            <span style="font-size: 14px;padding: 10px 0;">
              {{getDateFormatStr()}}
            </span>
          </i>
          <i class="el-icon-user" style="width: 130px;" @click="selectDingUser">
            <span style="font-size: 14px;padding: 10px 0;">
              {{ dataForm.assigneeName }}
            </span>
          </i>
          <i :class="`${dataForm.star?'el-icon-star-on':'el-icon-star-off'}`" @click="toggleStar"></i>
          <el-button type="primary" style="width:60px; height: 36px; position:absolute; right: -5px; top: -33px;" @click="saveTask">
            <i class="el-icon-check" style="padding: 0"></i>
          </el-button>
        </div>
        <div style="margin-right: 60px;">
          <table style="width: 100%">
            <tr>
              <td style="width: 50px;text-align: right">备注：</td>
              <td>
                <el-input type="textarea" :autosize="{ minRows: 1, maxRows: 3}" v-model="dataForm.remark"
                          placeholder="备注"  @focus="closeToolBox">  <!--@keyup.enter.native="saveTask"-->
                </el-input>
              </td>
            </tr>
          </table>
        </div>
        <div class="calendarTool" v-if="toolBoxVisible" >
          <div>
            <el-calendar v-model="dataForm.endDate">
            </el-calendar>
          </div>
        </div>
      </div>
    </div>
    <el-button type="primary" icon="el-icon-plus" class="add-button" :style="getStyle2()" circle @click="showPanel()"></el-button>
    <div style="position: fixed; left:60px; bottom: 20px; z-index: 3">
      <el-button v-if="listFlag!=3" circle @click="listFlag=3" style="width:40px;height: 40px;">
        <i  class="el-icon-date"></i>
      </el-button>
      <el-button v-if="listFlag==3" circle @click="listFlag=1" style="width:40px;height: 40px;">
        <i  class="el-icon-menu"></i>
      </el-button>
    </div>
  </div>
</template>

<script>
  import dingMixin from  '@/mixins/ding'
  import {dateUtil} from '@/utils/dateUtil'
  import * as dd from 'dingtalk-jsapi'

  export default {
    data () {
      return {
        query:{
          keyword:'',
          page: 1,
          limit: 5
        },
        detailWidth:480,
        todoList:[],
        hasDoList:[],
        todoCount: 0,
        listFlag: 0,
        totalPage: 0,
        dataLoading0: false,
        addVisible: false,
        addLoading:false,
        dataLoading: false,
        showCompleted:false,
        toolBoxVisible: false,
        detailMode:false,
        dataForm:{
          id:0,
          name:'',
          endDate:'',
          remark:'',
          star:false,
          assigneeId: '',
          assigneeName:'',
          creatorName:'',
          createAt:''
        }
      }
    },
    mixins: [dingMixin],
    created() {
      if (dd.env.platform!="notInDingTalk") {
        this.run_dd_config();
        this.clearSearch();
        if(this.userInfo && this.userInfo.dingId && this.dingConfig.corpId && this.$cookie.get('token')>'') {
          return;
        }
        this.getDingConfig().then(config =>{
          this.dingConfig = config;
          this.dingLogin(config.corpId, null);
        })
      }
    },
    mounted(){
      let that = this;
      window.history.pushState('forward', null, '/#/task-list');
      window.history.forward()
      window.addEventListener("popstate", function (e) {
        if (that.addVisible || that.detailMode){
          that.addVisible = false
          that.detailMode = false
        }else{
          //history.back();
          //alert('dd');
        }
      }, false);
    },
    methods: {
      navHelper(){
        window.location.href='/html/tdlHelper.html'
      },
      showAllTodo(){
        this.listFlag = 0
        this.$forceUpdate()
      },
      showTodayTodo(){
        this.dataLoading0 = true
        this.$nextTick(()=>{
          this.listFlag = 1
          this.dataLoading0 = false
          this.$forceUpdate()
        })
      },
      showExpiredList(){
        this.dataLoading0 = true
        this.$nextTick(()=>{
          this.listFlag = 2
          this.dataLoading0 = false
          this.$forceUpdate()
        })
      },
      getTodayTodoList(){
        return this.todoList.filter(x=>x.endDate == new Date().Format("yyyy-MM-dd"));
      },
      getExpiredList(){
        return this.todoList.filter(x=>x.endDate < new Date().Format("yyyy-MM-dd"));
      },
      getTodoListByDay(date){
        return this.todoList.filter(x=>x.endDate == new Date(Date.parse(date)).Format("yyyy-MM-dd"));
      },
      getHasDoListByDay(date){
        return this.hasDoList.filter(x=>x.endDate == new Date(Date.parse(date)).Format("yyyy-MM-dd"));
      },
      getToDoList(){
        if(this.listFlag == 1){
          return this.getTodayTodoList()
        }
        else if(this.listFlag == 2){
          return this.getExpiredList()
        }
        else if(this.listFlag == 3){
          return this.getTodoListByDay(this.dataForm.endDate)
        }
        else{
          return this.todoList
        }
      },
      getStyle(){
        if(this.isPC()){
          let w = this.detailMode?`padding-right: ${this.detailWidth}px;`:``
          return w+'font-size: 15px'
        }else{
          let w = this.detailMode?`display:none; `:``
          return w+'font-size: 16px'
        }
      },
      getStyle2(){
        if(this.isPC()){
          let w = this.detailMode?`right: ${this.detailWidth+20}px;`:``
          return w
        }
        return ''
      },
      getAssigneeStr(item){
        if(item.assigneeId == this.userInfo.dingId){
          if(item.creatorId != this.userInfo.dingId){
            return item.creatorName + '指派给我'
          }
        }
        else if(item.creatorId == this.userInfo.dingId){
          if(item.assigneeName>''){
            return '指派 '+ item.assigneeName
          }
        }
        return ''
      },
      getDateFormatStr(){
        console.log(this.dataForm.endDate.length)
        if(this.dataForm.endDate instanceof Date){
          return this.dataForm.endDate.Format("yyyy-MM-dd")
        }
        return this.dataForm.endDate
      },
      clearSearch(){
        this.query.keyword = ''
        this.search()
      },
      clearInput(){
        this.dataForm.id = 0;
        //this.dataForm.endDate = ''
        this.dataForm.assigneeName = ''
        this.dataForm.assigneeId = ''
        this.dataForm.star = false
        this.dataForm.name =''
        this.dataForm.remark = ''
      },
      search(){
        this.addVisible = false
        this.detailMode = false
        this.listFlag = 0
        this.query.page = 1;
        this.hasDoList = []
        this.getTodoTasks()
        this.getHasDoTasks()
      },
      loadMore(){
        this.query.page ++;
        //this.getHasDoTasks()
      },
      pageHasDoList(){
        let res = []
        if(this.listFlag!=3){
          for(let i=0; i<this.hasDoList.length && i<this.query.page*this.query.limit; i++){
            let item = this.hasDoList[i];
            res.push(item);
          }
        }
        else{
          return this.getHasDoListByDay(this.dataForm.endDate)
        }
        return res;
      },
      showPanel2(item){
        window.history.pushState('forward', null, '/#/task-list');
        window.history.forward()
        this.dataForm = JSON.parse(JSON.stringify(item))
        this.detailMode = true
        this.addVisible = false
      },
      showPanel(){
        window.history.pushState('forward', null, '/#/task-list');
        window.history.forward()
        this.clearInput()
        if(this.listFlag!=3){
          this.dataForm.endDate = new Date()
        }
        this.dataForm.assigneeId = this.userInfo.dingId
        this.dataForm.assigneeName = this.userInfo.realName
        this.addVisible=true
        this.detailMode = false
        this.$nextTick(()=>{
          this.$refs.txtTask.focus();
        })
      },
      saveTask(){
        this.addLoading = true
        this.$http({
          url: this.$http.adornUrl(`/tasklist/task/${!this.dataForm.id ? 'save' : 'update'}`),
          method: 'post',
          data: this.$http.adornData(this.dataForm)
        }).then(({data}) => {
            if (data && data.code === 0) {
              this.getTodoTasks()
              this.$message({message: '操作成功', type: 'success', duration: 1500})
              this.clearInput();
            }else{
              this.$message({message: data.message, type: 'error', duration: 1500})
            }
          }
        ).finally(()=>{
          this.addLoading=false
          this.addVisible=false
          this.detailMode=false
        })
      },
      calcTodoStatic(){
        this.todoCount = this.todoList.length
      },
      getTodoTasks(){
        if(this.dataLoading0){
          return;
        }
        this.dataLoading0 = true
        this.$http({
          url: this.$http.adornUrl(`/tasklist/task/todoList`),
          method: 'post',
          data: this.$http.adornData(this.query)
        }).then(({data}) => {
            if (data && data.code === 0) {
              this.todoList = data.data;
              if(this.query.keyword===''){
                 this.calcTodoStatic()
              }
            }
          }
        ).finally(()=>{
          this.dataLoading0 = false
        })
      },
      getHasDoTasks(){
        if(this.dataLoading){
          return;
        }
        this.dataLoading = true
        this.$http({
          url: this.$http.adornUrl(`/tasklist/task/hasDoList`),
          method: 'post',
          data: this.$http.adornData(this.query)
        }).then(({data}) => {
            if (data && data.code === 0) {
              this.hasDoList = this.hasDoList.concat(data.data.list);
              this.totalPage = data.data.list.length/this.query.limit+1
            }
          }
        ).finally(()=>{
          this.dataLoading = false
        })
      },
      toggleStar(){
        if(this.dataForm.flag){
          //disabled when completed
          return;
        }
        this.dataForm.star = !this.dataForm.star
      },
      setTaskStar(item){
        item.star = !item.star
        this.$http({
          url: this.$http.adornUrl(`/tasklist/task/update`),
          method: 'post',
          data: this.$http.adornData({id: item.id, star: item.star})
        }).then(({data}) => {
            if (data && data.code === 0) {

            }
          }
        )
      },
      setTaskStatus(item){
        this.$http({
          url: this.$http.adornUrl(`/tasklist/task/setStatus`),
          method: 'post',
          data: this.$http.adornData({id: item.id, flag: item.flag})
        }).then(({data}) => {
            if (data && data.code === 0) {
               if(item.flag){
                 item.completedDate = data.data.completedDate
                 this.hasDoList.unshift(item);
                 this.todoList = this.todoList.filter(x=>x.id!=item.id);
               }else{
                 this.todoList.push(item);
                 this.hasDoList = this.hasDoList.filter(x=>x.id!=item.id);
               }
               this.calcTodoStatic()
            }
          }
        )
      },
      closeToolBox(){
        if(!this.isPC()){
          this.$nextTick(()=>{
            this.toolBoxVisible=false
          })
        }
      },
      getDisabledUsers(){
        let d1 = this.unPermDingIds.split(',');
        let leaders = this.leaders.split(',');
        for(let t of leaders){
          d1 = d1.filter(x=>x!=t);
        }
        return d1;
      },
      selectDingUser(){
        if(this.dataForm.flag){
          //disabled when completed
          return;
        }
        this.complexPicker(1, this.getDisabledUsers() ,[]).then(
          data=>{
            console.log(JSON.stringify(data));
            if(data.length>0){
              this.dataForm.assigneeId = data[0].emplId
              this.dataForm.assigneeName = data[0].name
            }
          }
        )
      }
    }
  }
</script>

<style lang="scss">
  #main{
    .el-calendar__body{
      padding: 0;
    }
    .el-calendar__header{
      padding: 5px;
    }
    .el-calendar-table thead th{
      padding: 5px;
    }
    .el-calendar-table .el-calendar-day{
      height: 40px;
    }
  }

  #todo-task-panel,.drawer-right{
    .el-icon-star-off{
      font-size: 24px;
      color: #FF6100;
    }

    .el-icon-star-on{
      font-size: 29px;
      color: #FF6100;
    }

    .el-checkbox__inner{
      width:18px;
      height: 18px;
    }

    .el-checkbox__inner::after{
      left:5px;
      top:3px;
    }

    .el-checkbox__inner {
      border-color: gray;
    }
  }

  #hasDo-task-panel{
    .el-icon-star-off{
      font-size: 24px;
    }

    .el-icon-star-on{
      font-size: 29px;
    }

    .el-checkbox__inner{
      width:18px;
      height: 18px;
    }

    .el-checkbox__inner::after{
      left:5px;
      top:3px;
    }

  }

  .el-message-box__wrapper{
    z-index: 2;
  }

  .v-modal{
    z-index: 2;
  }

</style>

<style lang="scss" scoped>
  html,body{
    height:100%;
  }

  .calendarTool {
    height: 318px;
  }

  i{
    font-size: 16px;
    cursor: pointer;
  }

  .sub-title{
    width: 100%;
    height:48px;
    font-size: 20px;
    text-align: left;
    font-weight: bold;
  }

  .app-title {
    z-index: 3;
    text-align: center;
    background: white;
    position: fixed;
    width:100%;
    top:0;
    left:0;
    padding:6px 10px;
    height:48px;
    font-size: 16px;
    border-bottom: lightgray solid 1px;
  }
  .pj_container{
    width: 100%;
    margin: 48px 0;
    padding: 15px;
    overflow-y: auto;
  }

  .task-table{
    width:100%;
    /*max-width: 600px;*/
    margin: 0 auto;
    table-layout: fixed;
    line-height: 18px;
    tr{

    }
    td{
      padding: 10px 5px;
      min-width: 50px;
      vertical-align: top;
      cursor: pointer;
    }

    .small{
      font-size: 13px;color: #868EBF;
    }
  }

  .task-list-item{
    transition: all 1s;
  }

  .task-list-enter, .task-list-leave-to{
    opacity: 0;
    transform: translateY(50px);
/*    text-decoration: line-through;*/
  }

  .task-list-leave-active {
    position: absolute;
  }

  .add-button{
    position: fixed; bottom: 20px; right:20px; width:42px;height: 42px;
    z-index: 3;
    -webkit-filter: drop-shadow(2px 2px 2px gray); /* Chrome, Safari, Opera */
    filter: drop-shadow(2px 2px 2px gray);
  }

  .add-tool{
    position: fixed;
    bottom: 0;left: 0;
    padding: 10px;
    width:100%;
/*    height:90px;*/
    height: auto;
    background: white;
    z-index: 999;
  }

  .tool-box{
    position: relative;
    padding: 5px;
    i{
      padding: 10px;
      font-size: 20px;
    }
    .el-icon-star-on{
      color: #FF6100;
    }
  }

  .mode-btn{

  }

  .main-board{
    display:flex;
    width: 100%;
    height: 100%;
  }

  .drawer-right{
    width: 100%;
    max-width:480px;
    position: fixed;
    z-index: 10;
    right: 0px;
    top:48px;
    border-left: 1px solid lightgray;
    height:100%;
    padding: 15px;
    background: white;
  }

</style>

